package ro.fortech.peaa.web.controller;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import ro.fortech.peaa.domain.Employee;
import ro.fortech.peaa.domain.Job;
import ro.fortech.peaa.service.api.IEmployeeManager;
import ro.fortech.peaa.service.api.IJobManager;

public class EmployeeNewController extends AbstractController {

	private IEmployeeManager employeeManager;

	private IJobManager jobManager;

	public void setEmployeeManager(IEmployeeManager employeeManager) {
		this.employeeManager = employeeManager;
	}

	public void setJobManager(IJobManager jobManager) {
		this.jobManager = jobManager;
	}

	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		Map<String, Object> map = new HashMap<String, Object>();
		String errorMessage = "";

		String method = request.getMethod();
		logger.info("Method: " + method);

		if (method.equals(METHOD_GET)) {
			// get all jobs
			List<Job> jobs = jobManager.findAllIdAndTitle();
			map.put("jobs", jobs);
			map.put("error_message", "");

			logger.info("END");
			return new ModelAndView("employee_new", map);
		} else {
			Employee emp = new Employee();

			try {
				String firstName = request.getParameter("first_name");
				if (firstName != null && !firstName.equals("")) {
					emp.setFirstName(firstName);
				}
				String lastName = request.getParameter("last_name");
				if (lastName != null && !lastName.equals("")) {
					emp.setLastName(lastName);
				} else {
					errorMessage += " Last name cannot is empty!";
				}
				String email = request.getParameter("email");
				if (email != null && !email.equals("")) {
					emp.setEmail(email);
				} else {
					errorMessage += " Email is empty!";
				}
				String phone = request.getParameter("phone");
				if (phone != null && !phone.equals("")) {
					emp.setPhoneNumber(phone);
				}				
				String hireDate = request.getParameter("hire_date");
				if (hireDate != null && !hireDate.equals("")) {
					DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
					emp.setHireDate(dateFormat.parse(hireDate));
				} else {
					errorMessage += " Hire date is empty!";
				}
				
				String jobId = request.getParameter("job_id");
				if (jobId != null && !phone.equals("")) {
					emp.setJobId(jobId);
				} else {
					errorMessage += " Job id is empty!";
				}				

				String salary = request.getParameter("salary");
				if (salary != null && !salary.equals("")) {
					emp.setSalary(Double.parseDouble(salary));
				}

				String commissionPct = request.getParameter("commission_pct");
				if (commissionPct != null && !commissionPct.equals("")) {
					emp.setCommissionPct(Double.parseDouble(commissionPct));
				}

				String managerId = request.getParameter("manager_id");
				if (managerId != null && !managerId.equals("")) {
					emp.setManagerId(Integer.parseInt(managerId));
				}

				String departmentId = request.getParameter("department_id");
				if (departmentId != null && !departmentId.equals("")) {
					emp.setDepartmentId(Integer.parseInt(departmentId));
				}

				/* 
				 * Some fields do not accept null. Do not try to save if these
				 * fields are empty: LAST_NAME, EMAIL, HIRE_DATE, JOB_ID 
				 */
				if (errorMessage.equals("")) {
					logger.info("Before inserting employee.");
					employeeManager.insertEmployee(emp);
					logger.info("After inserting employee.");
				} else {
					logger.info("Do not save employee due to some issues: " + errorMessage);
					throw new Exception(errorMessage);
				}
			} catch (Exception e) {
				errorMessage = e.getMessage();
				logger.info("Adding new employee failed with error message " + errorMessage);
				map.put("error_message", errorMessage);
				// get all jobs
				List<Job> jobs = jobManager.findAll();
				map.put("jobs", jobs);
				return new ModelAndView("employee_new", map);
			}

			// Load employees
			List<Employee> employees = this.employeeManager.findAll();
			logger.info("Found " + employees.size() + " employees.");
			map.put("employees", employees);
			map.put("average_salary", employeeManager.getAverageSalary());
			return new ModelAndView("employees", map);
		}


	}

}
